﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Separation.Token;

namespace Separation.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
 
    public class UserController : ControllerBase
    {
        /// <summary>
        /// role仅仅是字符串 
        /// </summary>
        /// <returns></returns>

        [HttpGet("login")]
        [Authorize(Roles = "Admin")]
        public IActionResult Login()
        {
            return Ok(new { Message = "登录成功" });
        }

        [HttpGet("token")]
        public IActionResult GetToken() 
        {
            SecurityToken jwt = new JwtSecurityToken(
                issuer: "issuer",//jwt签发者,非必须
                audience: "audience",//jwt的接收该方，非必须
                claims: new Claim[]
                {
                new Claim("我吐了","真的奥"),
                //new Claim(ClaimTypes.Role ,"Admin"),
                new Claim(ClaimTypes.Role ,"User")
                }, //声明合集
                expires: DateTime.UtcNow.AddHours(24),//指定token的生命周期，unix时间戳格式,非必须
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("Chenlong1226550632")), SecurityAlgorithms.HmacSha256)
                );

            return Ok(new
            {
                Token = "Bearer " + new JwtSecurityTokenHandler().WriteToken(jwt)
            });
        }

        [HttpGet("token2")]
        public IActionResult GetToken2()
        {
            return Ok(new
            {
                Token = "Bearer " + new TokenHelper().TakeToken(new Token.Entity.TokenModel() { Uid = 122, Role = new RoleHelper().AddRole(Role.Admin,Role.Users)})
            });
        }
    }
}
